const ImageGenerationTask = require("../models/ImageGenerationTask");
const AiPerson = require("../models/AiPerson");

/**
 * 获取用户生成的AI图片
 * @param {Object} req - 请求对象，包含uuid参数和language查询参数
 * @param {Object} res - 响应对象
 */
exports.getUserGeneratedImages = async (req, res) => {
  try {
    console.log(`[DEBUG] 接收到请求: ${req.method} ${req.originalUrl}`);
    console.log(`[DEBUG] 请求体:`, req.body);

    const { uuid, language = "EN", page = 1, limit = 10 } = req.body; // 默认英文，添加分页参数

    // 验证请求
    if (!uuid) {
      return res.status(400).json({
        success: false,
        message: "缺少必要参数：uuid",
      });
    }

    // 验证分页参数
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);

    if (pageNum < 1 || limitNum < 1) {
      return res.status(400).json({
        success: false,
        message: "分页参数无效",
      });
    }

    // 查询用户的图片生成任务
    const imageTasks = await ImageGenerationTask.findAll({
      where: {
        user_uuid: uuid,
        status: "completed", // 只获取已完成的任务
        image_url: {
          [require("sequelize").Op.not]: null, // 确保有图片URL
        },
      },
      attributes: ["ai_person_id", "image_url", "created_at"],
      order: [["created_at", "DESC"]], // 按创建时间倒序
    });

    if (imageTasks.length === 0) {
      return res.status(200).json({
        success: true,
        message: "未找到生成的图片",
        data: [],
      });
    }

    // 获取所有涉及的AI角色ID
    const aiPersonIds = [
      ...new Set(
        imageTasks.map((task) => task.ai_person_id).filter((id) => id !== null)
      ),
    ];

    // 查询AI角色信息
    const aiPersons = await AiPerson.findAll({
      where: {
        id: aiPersonIds,
      },
      attributes: ["id", "avatar", "information"],
    });

    // 创建AI角色ID到角色信息的映射
    const aiPersonMap = {};
    aiPersons.forEach((person) => {
      // 从information字段中提取name字段作为username
      let username = "Unknown";
      const information = person.information || {};

      // 从information JSON字段中获取name
      if (information.name) {
        username = information.name;
      }

      aiPersonMap[person.id] = {
        avatar: person.avatar,
        username: username,
      };
    });

    // 按AI角色分组整理数据
    const groupedData = {};
    imageTasks.forEach((task) => {
      const aiPersonId = task.ai_person_id;

      // 如果ai_person_id为null或找不到对应的AI角色，跳过
      if (!aiPersonId || !aiPersonMap[aiPersonId]) {
        return;
      }

      if (!groupedData[aiPersonId]) {
        groupedData[aiPersonId] = {
          ai_person_id: aiPersonId,
          avatar: aiPersonMap[aiPersonId].avatar,
          username: aiPersonMap[aiPersonId].username,
          created_at: task.created_at, // 由于已按created_at倒序，第一个就是最新的
          Images: [task.image_url], // 只保存最新的一张图片
          imgsTotal: 1, // 初始化为1
        };
      } else {
        // 如果已存在该AI角色，增加图片总数
        groupedData[aiPersonId].imgsTotal++;
      }
    });

    // 转换为数组格式并按创建时间倒序排列
    const allResults = Object.values(groupedData).sort(
      (a, b) => new Date(b.created_at) - new Date(a.created_at)
    );

    // 计算分页
    const totalItems = allResults.length;
    const offset = (pageNum - 1) * limitNum;
    const paginatedResults = allResults.slice(offset, offset + limitNum);

    // 计算总的图片数量 (返回结果中所有AI角色的imgsTotal之和)
    const totalImgsCount = paginatedResults.reduce(
      (total, item) => total + item.imgsTotal,
      0
    );

    return res.status(200).json({
      success: true,
      message: "获取用户生成图片成功",
      data: paginatedResults,
      imgsTotal: totalImgsCount,
      totalItems: totalItems,
      currentPage: pageNum,
      totalPages: Math.ceil(totalItems / limitNum),
    });
  } catch (error) {
    console.error("获取用户生成图片错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

// 获取对应ai对应的生成的图片数据
exports.getAicollection = async (req, res) => {
  try {
    const { uuid, ai_person_id, page = 1, limit = 10 } = req.body;

    // 验证请求参数
    if (!uuid) {
      return res.status(400).json({
        success: false,
        message: "缺少必要参数：uuid",
      });
    }

    if (!ai_person_id) {
      return res.status(400).json({
        success: false,
        message: "缺少必要参数：ai_person_id",
      });
    }

    // 验证分页参数
    const pageNum = parseInt(page);
    const limitNum = parseInt(limit);

    if (pageNum < 1 || limitNum < 1) {
      return res.status(400).json({
        success: false,
        message: "分页参数无效",
      });
    }

    // 计算偏移量
    const offset = (pageNum - 1) * limitNum;

    // 查询条件
    const whereCondition = {
      user_uuid: uuid,
      ai_person_id: ai_person_id,
      status: "completed", // 只获取已完成的任务
      image_url: {
        [require("sequelize").Op.not]: null, // 确保有图片URL
      },
    };

    // 查询总数
    const totalCount = await ImageGenerationTask.count({
      where: whereCondition,
    });

    // 分页查询图片生成任务
    const imageTasks = await ImageGenerationTask.findAll({
      where: whereCondition,
      attributes: ["task_id", "image_url", "completed_at"],
      order: [["created_at", "DESC"]], // 按创建时间倒序
      limit: limitNum,
      offset: offset,
    });

    // 提取task_id和image_url数据到Images数组
    const Images = imageTasks.map((task) => ({
      task_id: task.task_id,
      image_url: task.image_url,
      completed_at: task.completed_at,
    }));

    return res.status(200).json({
      success: true,
      message: "获取AI角色图片集合成功",
      data: {
        Images: Images,
        total_count: totalCount,
      },
    });
  } catch (error) {
    console.error("获取AI角色图片集合错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};

/**
 * 删除用户的图片生成任务(支持单个或批量删除)
 * @param {Object} req - 请求对象，包含task_id(单个字符串或数组)
 * @param {Object} res - 响应对象
 */
exports.deleteImageTasks = async (req, res) => {
  try {
    const { task_id } = req.body;
    const user_uuid = req.visitor.uuid; // 从token中解析的访客uuid

    // 验证请求参数
    if (!task_id) {
      return res.status(400).json({
        success: false,
        message: "缺少必要参数：task_id",
      });
    }

    // 处理单个task_id或task_id数组
    const taskIds = Array.isArray(task_id) ? task_id : [task_id];

    // 首先验证所有待删除的任务是否都属于该用户
    const tasks = await ImageGenerationTask.findAll({
      where: {
        task_id: taskIds,
        user_uuid: user_uuid,
      },
    });

    // 如果找到的任务数量与请求的不一致，说明有些任务不存在或不属于该用户
    if (tasks.length !== taskIds.length) {
      return res.status(403).json({
        success: false,
        message: "部分或全部任务不存在或不属于当前用户",
      });
    }

    // 批量删除任务
    const deleteCount = await ImageGenerationTask.destroy({
      where: {
        task_id: taskIds,
        user_uuid: user_uuid,
      },
    });

    return res.status(200).json({
      success: true,
      message: "成功删除图片生成任务",
      data: {
        deleted_count: deleteCount,
      },
    });
  } catch (error) {
    console.error("删除图片生成任务错误:", error);
    return res.status(500).json({
      success: false,
      message: "服务器内部错误",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
};
